<?php
namespace TwinPeaks\Core;

class CContext
{
	private $template;
	
	/**
	 * @var array
	 */
	private $container = [];
	
	/**
	 * @return void
	 */
	function __construct($tplInstace)
	{
		$this->template = $tplInstace;
	}
	
	/**
	 * @return void
	 */
	final function setData(array $data)
	{
		$this->container = $data;
	}

	/**
	 * @return mixed
	 */
	function __get($name)
	{
		$methodName = self::propToMethod('get', $name);		
		$propValue = isset($this->container[$name]) ? $this->container[$name] : null;
		
		if (method_exists($this->template, $methodName))
			return call_user_func([$this->template, $methodName], $propValue);
		elseif (isset($this->container[$name]))
			return $this->container[$name];
		else
			return '';
	}
	
	/**
	 * @return void
	 */
	function __set($name, $value)
	{
		$methodName = self::propToMethod('set', $name);
		if (method_exists($this->template, $methodName))
			$this->container[$name] = call_user_func([$this->template, $methodName], $value);
		else
			$this->container[$name] = $value;
	}
	
	/**
	 * @return string
	 */
	static protected function propToMethod($prefix, $propName)
	{
		return $prefix . preg_replace('~_([a-z0-9])~e', 'strtoupper("$1")', $propName);
	}
	
	/**
	 * @return void
	 */
	function setTemplate($tplInstance)
	{
		$this->template = $tplInstance;
	}	
}